#include "cstdio"
#include "iostream"
#include "string"
#include "fstream"


using namespace std;

const int OP_SUCCESS = 0;
const int OP_FAILED = -1;

int GetProfileString(string file_name, string section_name, string item_name, string &item_value)
{
	ifstream mystream;
	mystream.open(file_name.c_str(), ios::in);
	if (!mystream)
	{
		cout << "Error " << endl;
		return -1;
	}

	char line[30];
	string line2;
	size_t return_of_find;
	bool found = false;
	while(mystream.getline(line, 30) && !found) //默认行不会超过30个字符
	{
		line2 = line;
		return_of_find = line2.find(section_name);
		if (string::npos == return_of_find)
		{
			continue; //没找到section项，则继续下一行读取
		}

		//找到了，则执行第二步，寻找相应的键值，关键是不能跨越多段
		while(mystream.getline(line, 30) && !found)
		{
			line2 = line;
			string equal_flag = "=";
			return_of_find = line2.find(equal_flag);

			if (string::npos == return_of_find)
			{
				//说明已经跨越了多段，目标寻找失败
				return -1;
			}

			//还在当前段中
			return_of_find = line2.find(item_name);
			if (string::npos == return_of_find)
			{
				//没有找到
				continue;
			}
			//找到了
			return_of_find = line2.rfind(" "); //要求配置文件=两边要有空格
			item_value = line2.substr(return_of_find + 1);
			found = true;
			if (' ' == item_value[0])
			{
				item_value = item_value.substr(1);
			}
		}
	}
	mystream.close();
	return 0;
}
int main(int argc, char* argv[])
{
	string file_name, item_value;
	file_name = "config.txt";
	GetProfileString(file_name, "section1", "age", item_value);
	cout << "section1,age=" << item_value << endl;
	GetProfileString(file_name, "section1", "name", item_value);
	cout << "section1,name=" <<item_value << endl;
	GetProfileString(file_name, "section2", "age", item_value);
	cout << "section2,age=" << item_value << endl;
	GetProfileString(file_name, "section2", "name", item_value);
	cout << "section2,name=" <<item_value << endl;
	return 0;
}